#!/bin/gawk -f

BEGIN{

# Inputs are
#	defaultfont
# 	outfile
#	showslide

# Parameters
	SliderHome="."
	SlideWidth=640
	SlideHeight=480
	doprint=0
	XOffset=60
	YOffset=50
	TitleSpace=40
	LevelSpace=30
	ItemSpace=20
	TextSpace=13
	BulletRad=3
	BulletColor="grey"
	BulletFill="black"
	TitleToContentDistance=40
	TitlePositionX=100
	TitlePositionY=200
	Indent["level1"]=15
	Indent["level2"]=40
	SlideBackground="none"
	Indicator="none"
	IndiPtr=""
	NextButton="none"
	PrevButton="none"
	

# defaults------
# Colors
	Color["background"]="white"	
	Color["title"]="black"
	Color["level1"]="black"
	Color["level2"]="black"
	Color["text"]="black"

#FontSize	
	FontSize["title"]="32pt"
	FontSize["level1"]="24pt"
	FontSize["level2"]="16pt"
	FontSize["text"]="14pt"

	Theme=""	
	OverrideTheme=0
	
# Preambule
	preambule=""
	
# Initialization
	name=""
	cur_slide=""
	tmpstr=""
	firstslide="yes"
	itm[1]=itm[2]=itm[3]=itm[4]=itm[5]=1
#	titleput=0
	nslide=0
#	ntitle=0
	nname=0
	nidx=1
	groupidx=0
	nfig=0
	ntex=0
	nbox=0
	nsrc=0
	nhid=0
	ntextbox=0
	fontcnt=0
	slidename=""
	status="parsing"
	figuresline=""
	sourcesline=""
	nmov=0
	
	# relative offsets
	# this is added to the figure coordinates
	# in fixcoord()
	relofsx=0
	relofsy=0
	
	# set by the calling program ruleron=1
	# or with $ruler command
	ruleron=0
	
	# use slide counter
	counter=1
	ackcnt=0
	totalslide=""
}


################# FUNCTIONS #######################

function trace(msg) {print msg > "/dev/stderr"}

function die(msg) {
	print msg > "/dev/stderr"
	status="failure"
	exit 1
}


# returns the value from a tag inside string. format: tag=value
#FIXME! how about space sourounding =
function extract(st,stag) {
	match(st,"\\<"stag"=#*[[:alnum:]\\.-_]*\\>%*",s);
	split(s[0],a,/=/)
	return a[2]
}

# fixing filename:
#   if filename has a preceeding / of ./ --> does not change
#   otherwise refers to SlideR homedir

function fixdir(st,dir) {
	if(match(st,/^\//)) return st
	if(match(st,/^\.\//)) return st
	if(dir) return SliderHome"/"dir"/"st
	else  return SliderHome"/"st
}

# fixing coordinates and geometries
# if the value is less than 1--> converted to relative coordinate (precentage)
# FIXME! relative offset

function fixcoord(st) {
	scrx=640-relofsx
	scry=480-relofsy
	
	if((xc=extract(st,"x"))!="") 
		if(xc<1.0)gsub(/\<x=[[:digit:]\.]*\>/,"x="(relofsx+int(xc*scrx)),st)
	if((wc=extract(st,"width"))!="")
		if(wc<1.0)gsub(/\<width=[[:digit:]\.]*\>/,"width="(relofsx+int(wc*scrx)),st)
	if((yc=extract(st,"y"))!="")
		if(yc<1.0)gsub(/\<y=[[:digit:]\.]*\>/,"y="(relofsy+int(yc*scry)),st)
	if((hc=extract(st,"height"))!="")
		if(hc<1.0)gsub(/\<height=[[:digit:]\.]*\>/,"height="(relofsy+int(hc*scry)),st)		

# for icons FIXME!
	if((ic=extract(st,"xicon"))!="")
		if(ic<1.0)gsub(/\<xicon=[[:digit:]\.]*\>/,"xicon="(relofsx+int(ic*scrx)),st)
	if((ic=extract(st,"iconwidth"))!="")
		if(ic<1.0)gsub(/\<iconwidth=[[:digit:]\.]*\>/,"iconwidth="(relofsx+int(ic*scrx)),st)
	if((ic=extract(st,"yicon"))!="")
		if(ic<1.0)gsub(/\<yicon=[[:digit:]\.]*\>/,"yicon="(relofsy+int(ic*scry)),st)		
	if((ic=extract(st,"iconheight"))!="")
		if(ic<1.0)gsub(/\<iconheight=[[:digit:]\.]*\>/,"iconheight="(relofsy+int(ic*scry)),st)

	return st
}

# put filename together with parameters
# line format:
#    sourcefile arg=val ....
# the rest of input string sc can be retrieved as {text} variable

function sourcefile(sc) {
	nsrc++
	split(sc,a)
	gsub(a[1],"",sc) # delete from line
	npar=0
	print "# sourching from "a[1]
	while(err = getline < a[1]) {
		if(err==-1) die("can not source from file: "a[1])
		if($1=="") continue
		if(match($0,/^#/)) continue
		# find parameter lists
		if(match($0,/^{[[:alnum:]]*}/)) {
			gsub(/[{}]/,"")
			npar++
			par[npar]=$1
			val[npar]=$2
			gsub(/[[:space:]]/,"",par[npar])
			# take defined value from line
			if (match(sc,"\\<"par[npar]"=#*[[:alnum:]\\.-_]*\\>%*",s)) {
				split(s[0],sv,/=/)
				val[npar]=sv[2]
				gsub(s[0]," ",sc) # delete from line
			}
		} else {
			# in the sourcefile, parameter is defined between 
			# curly bracket { } without space
			for(i=1;i<=npar;i++) gsub("{"par[i]"}",val[i])
			gsub(/{cnt}/,nsrc)
			gsub(/^[[:space:]]*/,"",sc)
			gsub(/{text}/,"\""sc"\"")
			# why doesn't it work? gsub(/"/,"\\\"")
			print
		}
	}
	print "# sourching ends"
	close(a[1])
}

# Put slide

function PutSlide() {
	if(nidx!=0) {
		# Title uses this offset--> indent=0
		X=XOffset
		Y=YOffset
		puttitle=1
		nsp=1  # FIXME! number of space
		split(NList[1], tag)
		
		if(slidestatus[nslide]!="hidden") {
			ackcnt++
			if(counter) {
				if(totalslide) cntxt=ackcnt"/"totalslide
				else cntxt=ackcnt
				print ".text cnt"nslide" "setstr["text"]" text=\""cntxt"\""
				print ".put cnt"nslide" x=610 y=20 scale=80% alpha=80%"
			}
		}
		
		if(tag[2]!="space") print ".put",tag[1],"x="X,"y="Y
		else if(tag[3]) nsp=tag[3];

		for(i=2;i<=nidx;i++){
			split(NList[i], tag)
		
			if(match(tag[1],/lvl/) && puttitle==1) {
				Y+=nsp*TitleToContentDistance
				puttitle=0
			}

			if(match(tag[1],/lvl2/)){
				Y+=nsp*ItemSpace;
				X0=Indent["level2"]
				withbullet=1
			}else if(match(tag[1],"lvl1")){
				Y+=nsp*LevelSpace;
				X0=Indent["level1"]
			}else{Y+=nsp*TitleSpace;X0=0}
		
			if(tag[2]=="space")continue
			
			if(tag[2]=="bullet"){
				print ".put "tag[1]"_bullet=bullet x="X+X0-10" y="Y-3*BulletRad
				print ".put "tag[1]" x="X+X0" y="Y
			}else print ".put "tag[1]" x="X+X0" y="Y
			nsp=1
		}
	}
	
#	trace("slide number "nslide)
	for (fig in figureline) print figureline[fig]
	for (sour in sourceline) sourcefile(sourceline[sour])
	delete figureline
	delete sourceline
	$0=""
	print ".end"
}

function setfont(whichf,filef) {
	Font[whichf]="font"fontcnt++
	FontFile[whichf]=fixdir(filef,"fonts")
	print ".font "Font[whichf]" "FontFile[whichf]
	setstr[whichf]="font="Font[whichf]" size="FontSize[whichf]" color="Color[whichf]
}

# reading theme file
function readtheme(themefile) {
	if(themefile) {
		UseTheme=fixdir(themefile,"themes")
		trace("Using theme: "UseTheme)
	
		while(err = getline < UseTheme) {
    		if(err==-1) die("can not read theme file: "themefile)
	    	if($1=="") continue
    		if(match($0,/^#/)) continue
    		if(match($0,/^Color[[:space:]]*{/)) {take="color";continue}
	    	if(match($0,/^Font[[:space:]]*{/)) {take="font";continue}
    		if(match($0,/}/)) {take="nothing";continue}
	    	if(take=="color")Color[$1]=$2
    		if(take=="font")setfont($1,$2)
		}
		setstr["theme"]=fixdir(themefile,"themes")
	}
	setstr["title"]="font="Font["title"]" size="FontSize["title"]" color="Color["title"]
	setstr["level1"]="font="Font["level1"]" size="FontSize["level1"]" color="Color["level1"]
	setstr["level2"]="font="Font["level2"]" size="FontSize["level2"]" color="Color["level2"]
	setstr["text"]="font="Font["text"]" size="FontSize["text"]" color="Color["text"]
	for(idx in setstr) setsaved[idx]=setstr[idx]
}

#FIXME!
# should be run before first slide

function firstsetup() {
	#save first the line
	savedst=$0

	defaultfont=SliderHome"/fonts/luxisr.swf"
	
	FontFile["title"]=defaultfont
	FontFile["level1"]=defaultfont
	FontFile["level2"]=defaultfont
	FontFile["text"]=defaultfont

	# default fonts
	preambule=preambule".font font"fontcnt" "FontFile["title"]"\n"	
	preambule=preambule".circle bullet r="BulletRad" color="BulletColor" fill="BulletFill"\n"

	# font definition name
	Font["title"]="font"fontcnt
	Font["level1"]="font"fontcnt
	Font["level2"]="font"fontcnt
	Font["text"]="font"fontcnt
	fontcnt++

	# read theme at first time
	readtheme(Theme)
	if(Theme)OverrideTheme=1

	print "#####################################"
	print "# Slider ver 0.1"
	print "#"
	print "# (c) Rosandi, 2007"
	print "#"
	print "# use: swfc <thisfilename> to compile"
	print "#\n"

	#restore the line
	$0=savedst
}

#########################################################

function dolatex(sc, opt){
	ntex++
	split(sc, txt, "\"")
	stextmp="latex_"ntex
	
	print "\\documentclass{report}" > stextmp".tex"
	print "\\usepackage{amsmath}" >> stextmp".tex"
	print "\\usepackage{color}" >> stextmp".tex"
	print "\\begin{document}" >> stextmp".tex"
	print "\\pagestyle{empty}" >> stextmp".tex"
	print "\\Huge\\noindent" >> stextmp".tex"
	
	if(opt=="equ") {
		print "\\begin{equation}" >> stextmp".tex"
	}
	
	print txt[2] >> stextmp".tex"
	
	if(opt=="equ") {
		print "\\nonumber" >> stextmp".tex"
		print "\\end{equation}" >> stextmp".tex"
	}
	
	print "\\end{document}" >> stextmp".tex"
	close(stextmp".tex")
	
	cmd="latex -interaction=nonstopmode "stextmp".tex >> slider.log 2>&1"
	cmd=cmd"&&dvips -E -D6000 -p 1 -l 1 -o "stextmp".eps "stextmp".dvi >> slider.log 2>&1"
	
	if (match(sc,/\<usejpg\>/)) {
		gsub(/\<usejpg\>/,"",txt[3])
		cmd=cmd"&& convert -antialias -quality 100 "stextmp".eps "stextmp".jpeg >> slider.log 2>&1"
		system(cmd)
		rsc=".jpeg "stextmp" "stextmp".jpeg\n"
	} else if (match(sc,/\<usepng\>/)) {
		gsub(/\<usepng\>/,"",txt[3])
		cmd=cmd"&&eps2eps -r9600 "stextmp".eps "stextmp"_r.eps"
		cmd=cmd"&& convert -transparent white -antialias -quality 100 "stextmp"_r.eps "stextmp".png >> slider.log 2>&1"
		system(cmd)
		rsc=".png "stextmp" "stextmp".png\n"		
	} else {
		cmd=cmd"&&epstopdf "stextmp".eps -o="stextmp".pdf >> slider.log 2>&1"
		cmd=cmd"&&pdf2swf "stextmp".pdf -o "stextmp".swf >> slider.log 2>&1"
		system(cmd) 
		rsc=".swf "stextmp" "stextmp".swf\n"
	}
	
	rsc=rsc".put "stextmp" "txt[3]"\n"
	return rsc
}

#########################################################

NR==1{firstsetup()}
$1==""{next}

#skip comments and take name of slide if exist
# name starts by #--- or #-->
# syntax:
#     #--> <slidename> requiredby <requiringslide>

/^#/{
	if ($1=="#---" || $1=="#-->"){
		slidename=$2
		slideref[slidename]="slide"(nslide+1)
		if($3=="requiredby") reqslide=$4
	}
	next
}

#combine continuing lines
/\\$/{
	tline=$0
	gsub(/\\$/,"",tline)
	while (match($0,/\\$/)){
		getline
		tline=tline" "$0
		gsub(/\\$/,"",tline)
	}
	$0=tline
}


####################Begin parsing########################

# if theme is defined from the command line disable this function
/^\$theme/{if(!OverrideTheme)readtheme($2);next}

# coordinate option
/^\$coord/&&$2{coordsys=$2}

#restore to previous font settings
/^\$font restore/{
	if(setsaved[$3]!="")setstr[$3]=setsaved[$3]
	next
}

/^\$font define/{
	Font[$3]=$4
	print ".font",$3,$4
	next
}

# changing font:
# $font title|level1|level2 [font=<newfont>] [size=<newsize>] [color=<newcolor>]

# font settings
/^\$font/{
	tt=$2
	setsaved[tt]=setstr[tt]
	tsize=extract($0,"size")
	tcolor=extract($0,"color")
	tfont=extract($0,"font")
	if(tsize)FontSize[tt]=tsize
	if(tcolor)Color[tt]=tcolor
	if(tfont)setfont(tt,tfont)	
	$1=$2=""
	setstr[tt]="font="Font[tt]" size="FontSize[tt]" color="Color[tt]
	next
}


/^\$offset/{XOffset=$2;YOffset=$3;next}
/^\$titlespace/{TitleSpace=$2;next}
/^\$levelspace/{LevelSpace=$2;next}
/^\$itemspace/{ItemSpace=$2;next}
/^\$textspace/{TextSpace=$2;next}
/^\$bulletradius/{BulletRad=$2;next}
/^\$bulletfill/{BulletFill="blue";next}
/^\$bulletcolor/{BulletColor="green";next}
/^\$titletocontentdistance/{TitleToContentDistance=$2;next}
/^\$titleposition/{TitlePositionX=$2;TitlePositionY=$3;next}
/^\$indent/{Indent[$2]=$3;next}

/^\$background/{
	SlideBackground=fixdir($2,"backgrounds");$1=$2=""
	SlideBackground=SlideBackground" "$0
	next
}

/^\$size/{
	split($2,a,"x");SlideWidth=a[1];SlideHeight=a[2]
	trace("slide size: "$2)
	trace("Warning! Size setting is still immature")
}

/^\$nextbutton/{
	NextButton=SliderHome"/buttons/"$2;$1=$2=""
	NextButton=NextButton" "$0
	next
}
/^\$prevbutton/{
	PrevButton=SliderHome"/buttons/"$2;$1=$2=""
	PrevButton=PrevButton" "$0
	next
}

# can be followed by options:
# x=<number> y=<number>

/^\$indicator/{
	Indicator=fixdir($2,"indicators");$1=$2=""
	trace("using indicator "Indicator)
	Indicator=Indicator" "$0
	next
}

/^\$slidepointer/{
	$1=""
	sub(/^[[:space:]]/,"")
	IndiPtr=$0
}

/^\$ruler/{ruleron=1;next}
/^\$counter on/{counter=1;next}
/^\$counter off/{counter=0;next}
/^\$totalslide/{totalslide=$2;next}

################################################
# defines group membership of a slide
# groupidx --> group counter always points to the current group
# Group --> array of group names
# GroupText --> group names in text format separated by '\n'

/^\$group/{
	groupidx++
	$1=""
	gsub(/^[[:space:]]*/,"")
	Group[groupidx]=$0
	GroupText=(GroupText)$0"\\n"
	next
}
############ Content ################

/^\$hidden/&&(nslide>0){
	if(current_obj!="skip"){nhid++;slidestatus[nslide]="hidden"}
	next
}

!/^\$slide/&&(current_obj=="skip"){next}

#### CREATING NEW SLIDE #####
# the status of a slide may alter 'after' this keyword
/^\$slide/{
	if (showslide=="all"||showslide==slidename||showslide==reqslide) { 
		nslide++
		slidename=""
		SlideGroup[nslide]=groupidx
		reqslide=""
		if (firstslide!="yes") PutSlide()
		firstslide="no"
		
		nidx=0; 
		delete NList
		
		print "\n\n############## NEW SLIDE: "slidename" ###############"
		print ".flash version=6 filename=slide"nslide".swf"
		print preambule
		
		$1=""
		cur_slide="slide"nslide
		name=cur_slide
		itm[1]=itm[2]=itm[3]=itm[4]=itm[5]=1
		current_obj="text title"
		slidestatus[nslide]="active"
	} else {current_obj="skip";next}
}

/^~/{
	lvl=gsub(/~/,"")
	name=cur_slide"_lvl"lvl"_itm"itm[lvl]++
	current_obj="text "lvl
	if (lvl==2) current_obj=current_obj" new"
}

# $figure filename x=100 y=100 scale=50%

/^\$figure/{
	nfig++;
	sub(/\$figure/,"fig"nfig)
	split($2, fname, ".")
	if(fname[2]=="jpg"||fname[2]=="jpeg") newfig=".jpeg fig_"nfig" "$2
	else if(fname[2]=="png") newfig=".png fig_"nfig" "$2
	else if(fname[2]=="swf"||fname[2]=="eps"||fname[2]=="pdf"||fname[2]=="ps") 
		newfig=".swf fig_"nfig" "fname[1]".swf"

	# Maybe some figures need conversion
	if(fname[2]=="eps") {
		cmd="epstopdf "$2" -o="fname[1]".pdf >> slider.log 2>&1"
		cmd=cmd"&&pdf2swf "fname[1]".pdf -o "fname[1]".swf >> slider.log 2>&1"
		cmd=cmd"&&rm "fname[1]".pdf"
		system(cmd)
	} else
	if(fname[2]=="ps") {
		# is ps just the same with eps for pictures??
		cmd="ps2pdf "$2" "fname[1]".pdf >> slider.log 2>&1"
		cmd=cmd"&&pdf2swf "fname[1]".pdf -o "fname[1]".swf"
		cmd=cmd"&&rm "fname[1]".pdf"
		system(cmd)
	} else
	if(fname[2]=="pdf") {
		cmd="pdf2swf "fname[1]".pdf -o "fname[1]".swf >> slider.log 2>&1"
		system(cmd)
	}
	
	$1=$2=""
	$0=newfig"\n.put fig_"nfig" "$0
	current_obj="figure picture"
}

# now I only accept swf movie
# returning line: player movie=moviename thumb=thumb.png .......

/^\$movieclip/{
	nmov++
	thethumb=extract($0,"thumb")
	if (thethumb=="") {
		thumb="ffmpeg -y -i "$2" -vframes 1 -ss 00:00:00 -an -vcodec png -f rawvideo mov_thumb_"nmov".png >> slider.log 2>&1"
		system(thumb)
		thethumb="mov_thumb_"nmov".png"
	}
	movname=$2
	if((player=extract($0,"effect"))=="") die("can not define movie effect")
	player=fixdir(player".mov","effects")
	$1=$2=""
	gsub(/effect=[[:alnum:]\._-]*/,"")
	$0=player" movie="movname" thumb="thethumb" "$0
	current_obj="source movie"	
}

# what to send to popup effect script?
# $2 slidename
# $3... effect=script_name options...

/^\$popup/{
	if((player=extract($0,"effect"))=="") die("can not define popup effect")
	player=fixdir(player".popup","effects")
	slidetopop=slideref[$2]
	if(slidetopop=="") die("can not find slide: "$2)
	gsub(/effect=[[:alnum:]\._-]*/,"");$1=$2=""
	$0=player" "$0" "setstr["text"]" "slidetopop".swf"
	current_obj="source popup"
}

/^\$box/{
	nbox++
	al="100%"
	$1=""

	if(x=extract($0,"x")=="")x=0
	if(y=extract($0,"y")=="")y=0
	if(al=extract($0,"alpha")=="")al="100%"
	
	gsub(/\<[xy]=[[:digit:]\.]*\>/, "")
	gsub(/\<alpha=[[:digit:]]*\%\>/,"")
	
	$0=".box box_"nbox" "$0
	$0=$0"\n.put box_"nbox" x="x" y="y" alpha="al"\n"
	current_obj="figure box"
}


# text filed accepts:
#   direct text when $2 sorounded by quotes ""
#   textfile name to display

/^\$text/{
	ntextbox++
	cmdtext=".edittext txt"ntextbox" text="
	if(!match($2,/"/))   #fake "
	{	
		textfile=$2;$2=""
		cmdtext=cmdtext"\""
		while(err = getline st < textfile){
			if(err==-1) die("can not open text file: "textfile)
			cmdtext=cmdtext""st"\\n"
		}
		cmdtext=cmdtext"\""
		close(textfile)
	} 

	# font must be defined previously using: $font define fontname fontfile
	
	if((fnt=extract($0,"font"))=="") $0=$0" font="Font["text"]
	else {
		setfont("font"ntextbox,fnt)
		$0=$0" font="Font["font"ntextbox]
	}
	
	if(extract($0,"size")=="")  $0=$0" size="FontSize["text"]
	if(extract($0,"color")=="") $0=$0" color="Color["text"]
	if(extract($0,"width")=="") $0=$0" width=320"
	if(extract($0,"height")=="")$0=$0" height=320"
	
	if((x=extract($0,"x"))=="") x=0
	if((y=extract($0,"y"))=="") y=0
	gsub(/\<y=[[:digit:]\.]*\>/," ")
	gsub(/\<x=[[:digit:]\.]*\>/," ")
	$1=cmdtext
	$0=$0" readonly wordwrap multiline noselect\n"
	$0=$0".put txt"ntextbox" x="x" y="y
	current_obj="figure text"
}

/^\$equation/{$0=dolatex($0,"equ");current_obj="figure equation"}
/^\$latex/{$0=dolatex($0,"");current_obj="figure latex"}
/^\$source/{$1="";current_obj="source"}

# future:
# Next-undefined text will have the last "current_obj value"!

#!!!! index() is buggy!!

{ # actions to be taken according to current_obj. $0 is the input
	if (match(current_obj, /^text/)) {
			if (match(current_obj,/title/)) {usefont=setstr["title"]}
			else if (match(current_obj,/1/)) {usefont=setstr["level1"]}
			else if(match(current_obj,/2/)) {usefont=setstr["level2"]}
			else {usefont=setstr["text"]}
			sub(/^[ ]*/,"")
			if ($0!="") {
				nidx++
				if (match($0, /^\{space/,a)) {
					gsub(/[\{\}]/,"",$0)
					option=$0
				} else
				# still keep this for compatibility				
				if (match($0, /^<space>/)) {
					option="space"
				} else				
				if(match(current_obj,/new/)) {
					option="bullet"
					gsub(/new/,"",current_obj)
				} else option="nobullet"

				NList[nidx]=name"_"nidx" "option
				print ".text "name"_"nidx" \""$0"\" "usefont
			}
	} # text
	else if(match(current_obj,/^figure/))figureline[figcnt++]=fixcoord($0)
	else if(match(current_obj,/^source/))sourceline[sourcnt++]=fixcoord($0)
}

END{
	if (status=="failure") exit 1;
	if(nslide==0) die("no slide to process: "showslide)
	PutSlide()

############### NAVIGATOR ###################

	print ".flash version=6 filename=navigator.swf"
	print preambule
	print ".box navbox width=230 height=480 color=black fill=black"
	print ".put navbox x=0 y=0"

	prevslide=0;nframe=0;navix=0;naviy=0;navist=101
	navshift=25.25
	print ".sprite iconscroll"
	print ".box naviconbox color="Color["background"]" fill="Color["background"]"  width=128 height=96"
	for(i=1;i<=nslide;i++) {
		if(slidestatus[i]=="hidden") continue
		nframe++
		print ".swf navshot"nframe" slide"i".swf"
		print ".sprite navthumb"nframe
		print "    .put naviconbox"
		print "    .put navshot"nframe" scale=20%"
		print ".end"
		print ".put navthumb"nframe" x="navix" y="naviy
		print ".button navbtn"nframe
		print "    .show naviconbox as=press alpha=80%"
		print "    .show naviconbox as=idle alpha=0%"
		print "    .show naviconbox as=hover alpha=40%"
		print "    .on_release:"
		print "       _root.navhandler("nframe");"
		print "    .end"
		print ".end"
		print ".put navbtn"nframe" x="navix" y="naviy
		naviy+=navist
	}
	print ".end"
	print ".put iconscroll x=80 y=5"
	print ".box boxscrollbtn height=20 width=15 color=grey fill=grey"
	print ".text tnavdown text=\"dn\" "setstr["text"]
	print ".text tnavup text=\"up\" "setstr["text"]
	print ".sprite navdown"
	print "    .put boxscrollbtn"
	print "    .put tnavdown y=15"
	print ".end"
	print ".sprite navup"
	print "    .put boxscrollbtn"
	print "    .put tnavup y=15"
	print ".end"
	print ".action:"
	print "    var intID;"
	print "    function shiftdown() {if(iconscroll._y>"(-(nframe-3)*navist+5)")iconscroll._y-="navshift";}"
	print "    function shiftup() {if(iconscroll._y<"2*navist")iconscroll._y+="navshift";}"
	print ".end"     
	print ".button navscrollup"
	print "    .show navup as=idle alpha=50%"
	print "    .show navup as=hover alpha=50%"
	print "    .show navup as=press alpha=80%"
	print "    .show boxscrollbtn as=area"
	print "    .on_press: intID=setInterval(shiftup, 10); .end"
	print "    .on_release: clearInterval(intID); .end"
	print ".end"
	print ".button navscrolldown"
	print "    .show navdown as=idle alpha=50%"
	print "    .show navdown as=hover alpha=50%"
	print "    .show navdown as=press alpha=80%"
	print "    .show boxscrollbtn as=area"
	print "    .on_press: intID=setInterval(shiftdown, 10); .end"
	print "    .on_release: clearInterval(intID); .end"
	print ".end"
	print ".put navscrollup x=213 y=420"
	print ".put navscrolldown x=213 y=450"
	print ".end\n\n"
	
############MAIN SLIDE ARRANGEMENT#################
	

	print "\n\n################## MAIN SWFC CODE ###################"	
	print ".flash filename="outfile" bbox="SlideWidth"x"SlideHeight" fps=12 version=6"
	
	print preambule
	
# Initial action script
	print ".action:"
	print "  sprocent=0;countdown=3;navshown=false;"
	print "  function decreasecounter() {if(countdown<=0) {Mouse.hide();}else countdown--;};"
	print "  onMouseMove=function(){"
	print "      Mouse.show();"
	print "      countdown=3;};"
	print "  listenkey=new Object();"
	print "  listenkey.onKeyDown=function() {"
	print "  switch(Key.getCode()) {"
	print "      case Key.PGDN: nextFrame();break;"
	print "      case Key.ENTER: nextFrame();break;"
	print "      case Key.SPACE: nextFrame();break;"
	print "      case Key.PGUP: prevFrame();break;"
	print "      case Key.BACKSPACE: prevFrame();}};"
	print "  Key.addListener(listenkey);"
	print "  setInterval(decreasecounter,1000);"
	print "	 gotoFrame(0);"
	print "  function navhandler(frm){gotoFrame(frm);navigator._x=-400;navshown=false;};"
	print ".end"

#	print "      case Key.ENTER: if(_currentframe==1) gotoFrame(2); else nextFrame(); break;"
#	print "      case Key.SPACE: gotoFrame(_root._currentframe+1);break;"
#	print "      case Key.BACKSPACE: prevFrame();}};"
	
	# BACKGROUND
	# if filetype is .sc --> sourcefile.
	# The script must put the background, not here!
	
	if(SlideBackground=="none"){
		print ".box slidebackg color="Color["background"]" fill="Color["background"]" width=640 height=480"
		print ".put slidebackg x=0 y=0"
	}else{
		trace("using background: "SlideBackground)
		if (match(SlideBackground, /\.sc\>/)) sourcefile(SlideBackground)
		else{
			if (match(SlideBackground, /\.png\>/)) print ".png slidebackg "SlideBackground
			if (match(SlideBackground, /\.jpg\>/)) print ".jpeg slidebackg "SlideBackground
			if (match(SlideBackground, /\.jpeg\>/)) print ".jpeg slidebackg "SlideBackground
			if (match(SlideBackground, /\.swf\>/)) print ".swf slidebackg "SlideBackground
			print ".put slidebackg x=0 y=0"
		}
	}
	
    # source NextButton
	if (NextButton=="none") {
		print ".box next color="Color["background"]" fill="Color["background"]"  width=200 height=1200"
		print ".button nextbtn"
		print "    .show next as=press"
		print "    .show next as=shape"
		print "    .show next as=hover"
		print "    .on_release:"
		print "       nextFrame();"
		print "    .end"
		print ".end"
		print ".put nextbtn alpha=0 x=600 y=-100"
	} else {
		if(match(NextButton,/[[:alnum:]\/\.]*\.swf\>/,btn)) {
			print ".swf next \""btn[0]"\""
			print ".button nextbtn"
            print "    .show next as=idle"
			print "    .on_release:"
			print "       nextFrame();"
			print "    .end"
			print ".end"
			gsub(btn[0],"",NextButton)
			print ".put nextbtn "NextButton
		} else if(match(NextButton,/[[:alnum:]\/\.]*\.png\>/,btn)) {
			print ".png next \""btn[0]"\""
			print ".button nextbtn"
            print "    .show next as=press"
			print "    .show next as=shape"
			print "    .show next as=hover"
			print "    .on_release:"
			print "       nextFrame();"
			print "    .end"
			print ".end"
			gsub(btn[0],"",NextButton)
			print ".put nextbtn "NextButton
		} 
		else sourcefile(NextButton )
	}

# source PrevButton
	if(PrevButton=="none"){
		print ".box prev color="Color["background"]" fill="Color["background"]"  width=200 height=1200"
		print ".button prevbtn"
		print "    .show prev as=idle"
		print "    .on_release:"
		print "       prevFrame();"
		print "    .end"
		print ".end"
		print ".put prevbtn alpha=0 x=-150 y=30"
	} else {
		if(match(PrevButton,/[[:alnum:]\/\.]*\.swf\>/,btn)) {
			print ".swf prev \""btn[0]"\""
			print ".button prevbtn"
			print "    .show prev as=press"
			print "    .show prev as=shape"
			print "    .show prev as=hover"
			print "    .on_release:"
			print "       prevFrame();"
			print "    .end"
			print ".end"
			gsub(btn[0],"",PrevButton)
			print ".put prevbtn "PrevButton
		} else if(match(PrevButton,/[[:alnum:]\/\.]*\.png\>/,btn)) {
			print ".png prev \""btn[0]"\""
			print ".button prevbtn"
            print "    .show prev as=press"
			print "    .show prev as=shape"
			print "    .show prev as=hover"
			print "    .on_release:"
			print "       prevFrame();"
			print "    .end"
			print ".end"
			gsub(btn[0],"",PrevButton)
			print ".put prevbtn "PrevButton
		} else
		sourcefile(PrevButton)
	}
	
	print ".box navi color=grey fill=grey width=230 height=120"
	print ".button navbtn"
	print "    .show navi as=idle alpha=0%"
	print "    .show navi as=hover alpha=5%"
	print "    .show navi as=press alpha=5%"
	print "    .on_release: "
	print "		if(navshown){navigator._x=-400;navshown=false;}"
	print "		else {navigator._x=-70;navshown=true;};"
	print "	   .end"
	print ".end"
	print ".put navbtn x=-100 y=-100"
	print ".swf navigator navigator.swf"
	
# now create frames
# FIXME!
# pitfall: deletion of wrong slide when moving backward or jump
#          up to now --> no problem
	
	# mask the presentation only withing the slide size
	# fixme!
	print ".box topbot width="SlideWidth*3" height="SlideHeight" line=0 color=white fill=white"
	print ".box leftright width="SlideWidth" height="SlideHeight" line=0 color=black fill=black"
	
	if(ruleron) {
		trace("putting ruler")
		print ".png ruler "SliderHome"/images/ruler.png"
		print ".put ruler x=0 y=0 alpha=50%"
	}
	if(counteron) {
		print ".put cnttext x=620 y=470 scale=50% alpha=60%"
	}
	
	prevslide=0
	nframe=0
	lastindicator=""
	for(isli=1;isli<=nslide;isli++) {
#	print "nslide: "nslide" status: "slidestatus[i] > "/dev/stderr"
		trace("Creating slide "isli"/"nslide)
		if(slidestatus[isli]=="hidden") continue
		ackslide++
		print ".frame",++nframe
		if (prevslide>0) {
			print ".del slide"prevslide
			print ".del navigator"
		}
		prevslide=isli;

		pct=(nslide==1)?100:(nframe*100/(nslide-nhid))
		# source Indicator
		if (Indicator!="none" && isli>1&&SlideGroup[isli]) {
			# delete last indicator
			if(lastindicator) print ".del "lastindicator
			tmptext=GroupText
			sub(Group[SlideGroup[isli]],"&"IndiPtr,tmptext)
			sourcefile(Indicator" id="isli" progress="pct" slidegroup="isli" "tmptext)
			lastindicator="TheIndicator_"isli
		}
		
		print ".swf slide"isli" slide"isli".swf"
		print ".put slide"isli
		print ".put navigator x=-400 y=0 alpha=75%"
#		if(doprint==1) print ".action: printAsBitmap(\"slide"i"\",\"bframe\"); .end"
		print ".put topmask"isli"=topbot x=-"SlideWidth" y=-"SlideHeight
		print ".put botmask"isli"=topbot x=-"SlideWidth" y="SlideHeight
		print ".put leftmask"isli"=leftright x=-"SlideWidth" y=0"
		print ".put rightmask"isli"=leftright x="SlideWidth" y=0"
		if(ruleron) {
			print ".del ruler"
			print ".put ruler x=0 y=0 alpha=50%"
		}
	}
	print ".end"
	
	print "Total slide:", nslide > "/dev/stderr"
	print "Active:", ackcnt > "/dev/stderr"
	print "Hidden:", nhid > "/dev/stderr"
	
}
